import request from "../helpers/request";
import { friendlyDate } from "../helpers/utils";
const URL = {
    GET: '/notes/from/:notebookId',
    UPDATE: '/notes/:noteId',
    DELETE: '/notes/:noteId',
    ADD:'/notes/to/:notebookId'
}
export default {
    getNotes({ notebookId }) {

        return new Promise((resolve, reject) => {
            request(URL.GET.replace(':notebookId', notebookId), 'GET').then((res) => {
                res.data = res.data.map(note => {
                    note.friendlyCreatedAt = friendlyDate(note.createdAt)
                    note.friendlyUpdatedAt = friendlyDate(note.updatedAt)
                    return note
                }).sort((note1, note2) => {
                    note2.createdAt.localeCompare(note1.createdAt)
                })
                
                resolve(res)
            }).catch((res) => {
                reject(res)
            })
        })
       
        
    },
    updateNote({ noteId }, { title, content }) {
      return  request(URL.UPDATE.replace(':noteId', noteId), 'PATCH', { title, content })
    },
    deleteNote({ noteId }) {
       return request(URL.DELETE.replace(':noteId', noteId), 'DELETE')
    },
    addNote({ notebookId }, { title = '', content = '' } = { title: '', content: '' }) {

        return new Promise((resolve, reject) => {
            request(URL.ADD.replace(':notebookId', notebookId), 'POST', { title, content }).then((res) => {
                res.data.friendlyCreatedAt = friendlyDate(res.data.createdAt)
                res.data.friendlyUpdatedAt = friendlyDate(res.data.updatedAt)
                resolve(res)
                
            }).catch((res) => {
                reject(res)
            })
        })
      
    }
}